/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"fmt"
	"net"
	"strconv"
	"time"

	"github.com/spf13/cobra"
)

func CheckPort(host string, port int, timeout time.Duration) bool {
	address := fmt.Sprintf("[%s]:%d", host, port)
	conn, err := net.DialTimeout("tcp", address, timeout)
	if err != nil {
		return false
	}
	defer conn.Close()
	return true
}

// telnetCmd represents the telnet command
var telnetCmd = &cobra.Command{
	Use:   "telnet",
	Short: "检查服务器端口是否连通",
	Long:  `检查服务器端口是否连通，必须两个参数：HOST  PORT`,
	Args:  cobra.ExactArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("checking: ", args[0], args[1])
		num, err := strconv.Atoi(args[1])
		if err != nil {
			fmt.Println("端口格式错误!")
			return
		}
		if CheckPort(args[0], num, 3*time.Second) {
			fmt.Println("established")
		} else {
			fmt.Println("not established")
		}
	},
}

func init() {
	rootCmd.AddCommand(telnetCmd)
}
